package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.OrderConstant;
import com.sky.constant.PayConstant;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageBean;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.service.OrderDetailService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.BaiduLbsYunUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.ThreadLocalUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * C端订单业务接口实现类
 *
 * @Author Vsunks.v
 * @Date 2023/5/9 10:58
 * @Blog blog.sunxiaowei.net
 * @Description:
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     *
     * @param orderSubmitDTO 用户订单详情
     * @return
     */
    @Override
    @Transactional
    public Result<OrderSubmitVO> submit(OrderSubmitDTO orderSubmitDTO) throws UnsupportedEncodingException {

        // 0. 异常情况处理（购物车为空、收货地址为空、超出配送范围）
        // 0.1 查询购物车，并判断
        List<ShoppingCart> shoppingCarts = shoppingCartService.list().getData();
        if (shoppingCarts == null || shoppingCarts.size() <= 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 0.2 查询地址，并判断
        // List<AddressBook> books = addressBookService.list(AddressBook.builder().id(orderSubmitDTO.getAddressBookId()).build());
        AddressBook addressBook = addressBookService.getById(orderSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }


        // 检查用户位置是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());


        // 1. 组织订单数据
        Order order = new Order();
        BeanUtils.copyProperties(orderSubmitDTO, order);

        // 1.x 组织订单基本信息
        order.setNumber(UUID.randomUUID().toString().replace("-", ""));
        order.setStatus(OrderConstant.PENDING_PAYMENT);
        order.setUserId(ThreadLocalUtil.getCurrentId());
        order.setOrderTime(LocalDateTime.now());
        order.setPayMethod(1);
        order.setPayStatus(PayConstant.UN_PAID);

        // 收货人信息
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());


        // 2. 保存订单，并获取订单id
        if (orderMapper.insert(order) < 1) {
            throw new OrderBusinessException(MessageConstant.ORDER_BASIC_SAVE_FAIL);
        }

        // 1.x 查询当前登录用户的购物车
        // 2.x 组织订单明细
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        Long orderId = order.getId();
        shoppingCarts.forEach(sc -> {
            OrderDetail od = new OrderDetail();
            BeanUtils.copyProperties(sc, od, "id");
            od.setOrderId(orderId);
            orderDetails.add(od);
        });


        // 保存订单明细
        if (!orderDetailService.saveBacth(orderDetails)) {
            throw new OrderBusinessException(MessageConstant.ORDER_DETAIL_SAVE_FAIL);
        }

        // 清空购物车
        shoppingCartService.clean();


        // TODO  默认已经支付完成，调用支付成功的方法，修改订单状态、支付状态、来单提示
        // paySuccess(order.getNumber());

        // 组织数据，并返回
        OrderSubmitVO submitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        // 下单成功后，默认支付成功
        paySuccess(order.getNumber());

        return Result.success(submitVO);
    }


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 订单支付
     *
     * @param orderPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrderPaymentDTO orderPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                orderPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    @Transactional
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = ThreadLocalUtil.getCurrentId();

        // 根据订单号查询当前用户的订单
        Order orderInDb = orderMapper.selectByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        orderInDb.setStatus(OrderConstant.TO_BE_CONFIRMED);
        orderInDb.setPayStatus(PayConstant.PAID);
        orderInDb.setCheckoutTime(LocalDateTime.now());

        orderMapper.updateById(orderInDb);

        // 通知商家管理端，有订单请接单
        // 组织数据
        Map msgMap = Map.of("type", 1, "orderId", orderInDb.getId(), "content", "来订单了，请注意接单~！");

        // 发送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(msgMap));

    }


    /**
     * 用户端订单分页查询(stream流方式)
     *
     * @param pageNum  页码
     * @param pageSize 页面大小
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @Override
    public PageBean pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 0. 设置分页查询条件
        PageHelper.startPage(pageNum, pageSize);

        // 1. 封装查询条件并查询订单
        OrderPageQueryDTO ordersPageQueryDTO = new OrderPageQueryDTO();
        ordersPageQueryDTO.setUserId(ThreadLocalUtil.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Order> page = (Page<Order>) orderMapper.listByConditions(ordersPageQueryDTO);

        // 2. 封装到OderVO中
        List<OrderVO> orderVOS = null;
        // ******************使用stream流的方式防封装*******************
        // 2.1 查询出订单明细，并封装入OrderVO集合并返回
        if (page != null && page.getTotal() > 0) {
            orderVOS = page.getResult().stream().map(order -> {
                // 2.2 根据订单id查询订单明细列表
                List<OrderDetail> orderDetails = orderDetailService.listByOrderId(order.getId());

                // 2.3 创建OrderVO对象并封装数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                return orderVO;
            }).collect(Collectors.toList());


        }
        // 3. 封装到PageBean中并返回
        return new PageBean(page.getTotal(), orderVOS);
    }


    /**
     * 用户端订单分页查询（传统方式）
     *
     * @param pageNum  页码
     * @param pageSize 页面大小
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    // @Override
    public PageBean pageQuery4User1(int pageNum, int pageSize, Integer status) {
        // 0. 设置分页查询条件
        PageHelper.startPage(pageNum, pageSize);

        // 1. 封装查询条件并查询订单
        OrderPageQueryDTO ordersPageQueryDTO = new OrderPageQueryDTO();
        ordersPageQueryDTO.setUserId(ThreadLocalUtil.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Order> page = (Page<Order>) orderMapper.listByConditions(ordersPageQueryDTO);

        // 2. 封装到OderVO中
        List<OrderVO> orderVOS = new ArrayList();

        // ******************使用传统方式封装数据*******************
        // 2.1 查询出订单明细，并封装入OrderVO集合并返回
        if (page != null && page.getTotal() > 0) {
            for (Order order : page) {
                // 2.2 根据订单id查询订单明细列表
                List<OrderDetail> orderDetails = orderDetailService.listByOrderId(order.getId());

                // 2.3 创建OrderVO对象并封装数据
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                // 2.4 添加到OrderVO集合
                orderVOS.add(orderVO);
            }
        }
        // 3. 封装到PageBean中并返回
        return new PageBean(page.getTotal(), orderVOS);
    }


    /**
     * 根据订单id查询订单（含订单详情）
     *
     * @param id 订单Id
     * @return 指定id的订单（含订单详情）
     */
    @Override
    public OrderVO findByIdWithDetails(Long id) {
        // 根据id查询订单基本信息
        Order order = orderMapper.selectById(id);

        // 根据订单id查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetais = orderDetailService.listByOrderId(order.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetais);

        return orderVO;
    }

    /**
     * 用户取消订单，根据id取消订单
     *
     * @param id 订单id
     * @return
     * @throws Exception 查无此单
     */
    @Override
    public boolean userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Order orderInDb = orderMapper.selectById(id);

        // 校验订单是否存在
        if (orderInDb == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 订单状态为已接单及之后状态，需要联系商家取消
        if (orderInDb.getStatus() >= OrderConstant.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 订单处于待接单状态下取消，需要进行退款
        if (OrderConstant.TO_BE_CONFIRMED.equals(orderInDb.getStatus())) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orderInDb.getNumber(), //商户订单号
                    orderInDb.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orderInDb.setPayStatus(PayConstant.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orderInDb.setStatus(OrderConstant.CANCELLED);
        orderInDb.setCancelReason(MessageConstant.ORDER_CANCLE_BY_USER);
        orderInDb.setCancelTime(LocalDateTime.now());
        return orderMapper.updateById(orderInDb) > 0;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public boolean repetition(Long id) {
        // 查询当前用户id
        Long userId = ThreadLocalUtil.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetails = orderDetailService.listByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        return shoppingCartService.saveBatch(shoppingCarts);
    }

    /**
     * 分页、条件查询订单
     *
     * @param orderPageQueryDTO 查询条件、分页条件
     * @return 符合要求的订单集合
     */
    @Override
    public PageBean pageByCondition(OrderPageQueryDTO orderPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());

        // 按照条件查询所有，Mybatis分页插件PageHelper会自动将该查询调整为分页查询
        Page<Order> orderPage = (Page<Order>) orderMapper.listByConditions(orderPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Order转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(orderPage);

        return new PageBean(orderPage.getTotal(), orderVOList);
    }

    /**
     * 将List<Order>封装为List<OrderVO>，为每个订单添加菜品(套餐)的名称和数量
     *
     * @param orderPage 包含List<Order>的分页对象
     * @return 新的List<OrderVO>
     */
    private List<OrderVO> getOrderVOList(Page<Order> orderPage) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOs = new ArrayList<>();

        List<Order> orders = orderPage.getResult();
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order Order : orders) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(Order, orderVO);
                String orderDishes = getOrderDishesStr(Order);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOs.add(orderVO);
            }
        }
        return orderVOs;
    }

    /**
     * 根据订单id获取其中菜品（名称和数量）信息
     *
     * @param order 包含订单id的订单对象
     * @return 由所有菜品名称和数量拼接而成的字符串
     */
    private String getOrderDishesStr(Order order) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetails = orderDetailService.listByOrderId(order.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetails.stream().map(orderDetail -> {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 查询并统计各个状态的订单数量统计
     *
     * @return 各个状态的订单的数量
     */
    @Override
    public OrderStatisticsVO statisticsByStatus() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countByStatus(OrderConstant.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countByStatus(OrderConstant.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countByStatus(OrderConstant.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 商家接单
     *
     * @param orderConfirmDTO 订单id和目标状态
     * @return 是否接单成功
     */
    @Override
    public boolean confirmById(OrderConfirmDTO orderConfirmDTO) {
        // 构建含有订单id和订单目标状态的对象
        Order order = Order.builder()
                .id(orderConfirmDTO.getId())
                .status(OrderConstant.CONFIRMED)
                .build();

        // 调用Mapper根据id更新订单状态
        return orderMapper.updateById(order) > 0;
    }


    /**
     * 商家拒单
     *
     * @param orderRejectionDTO 订单id和拒单原因
     * @return 拒单是否成功
     */
    @Override
    public boolean rejectionById(OrderRejectionDTO orderRejectionDTO) throws Exception {
        // 根据id查询订单
        Order orderInDb = orderMapper.selectById(orderRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (orderInDb == null || !orderInDb.getStatus().equals(OrderConstant.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 已支付的订单需要退款
        Integer payStatus = orderInDb.getPayStatus();
        if (Order.PAID.equals(payStatus)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderInDb.getNumber(),
                    orderInDb.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            // log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Order order = new Order();
        order.setId(orderInDb.getId());
        order.setStatus(OrderConstant.CANCELLED);
        order.setRejectionReason(orderRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());

        // 组织数据并返回
        return orderMapper.updateById(order) > 0;
    }

    /**
     * 管理端取消订单
     *
     * @param orderCancelDTO 订单id和取消原因
     * @return 是否取消成功
     * @throws Exception 退款相关异常
     */
    @Override
    public boolean cancelById(OrderCancelDTO orderCancelDTO) throws Exception {
        // 根据id查询订单
        Order orderDB = orderMapper.selectById(orderCancelDTO.getId());

        // 如果是已支付，则需要申请退款
        Integer payStatus = orderDB.getPayStatus();
        if (PayConstant.PAID.equals(payStatus)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderDB.getNumber(),
                    orderDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            // log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Order order = new Order();
        order.setId(orderCancelDTO.getId());
        order.setStatus(Order.CANCELLED);
        order.setCancelReason(orderCancelDTO.getCancelReason());
        order.setCancelTime(LocalDateTime.now());

        // 组织数据并返回
        return orderMapper.updateById(order) > 0;
    }

    /**
     * 派送订单（只有待派送的订单，才可以点击派送订单）
     *
     * @param id 订单id
     * @return 是否修改成功
     */
    @Override
    public boolean deliveryById(Long id) {
        // 根据id查询订单
        Order orderInDb = orderMapper.selectById(id);

        // 校验订单是否存在，并且状态为3
        if (orderInDb == null || !OrderConstant.CONFIRMED.equals(orderInDb.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Order order = new Order();
        order.setId(orderInDb.getId());
        // 更新订单状态,状态转为派送中
        order.setStatus(OrderConstant.DELIVERY_IN_PROGRESS);
        return orderMapper.updateById(order) > 0;
    }

    @Override
    public boolean completeById(Long id) {
        // 根据id查询订单
        Order orderInDB = orderMapper.selectById(id);

        // 校验订单是否存在，并且状态为4
        if (orderInDB == null || !OrderConstant.DELIVERY_IN_PROGRESS.equals(orderInDB.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orderInDB.setId(orderInDB.getId());
        // 更新订单状态,状态转为完成
        orderInDB.setStatus(Order.COMPLETED);
        orderInDB.setDeliveryTime(LocalDateTime.now());

        // 组织数据并返回
        return orderMapper.updateById(orderInDB) > 0;
    }

    /**
     * C端用户催单
     *
     * @param id 订单id
     * @return 是否成功
     */
    @Override
    public boolean reminderById(Long id) {
        // 参数校验
        // 如果订单不存在，则不允许催单
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 组织催单数据
        Map msgMap = Map.of("type", 2,
                "orderId", id,
                "content", "用户催单了，赶快做好了配送过去！"
        );

        // 通过websocket发送消息给前端
        webSocketServer.sendToAllClient(JSON.toJSONString(msgMap));

        return true;
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) throws UnsupportedEncodingException {
        Map paramsMap = new LinkedHashMap();
        paramsMap.put("address", shopAddress);
        paramsMap.put("output", "json");
        paramsMap.put("ak", ak);


        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", paramsMap);


        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            String msg = jsonObject.getString("message");
            throw new OrderBusinessException("店铺地址解析失败：" + msg);
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        paramsMap.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", paramsMap);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            String msg = jsonObject.getString("message");
            throw new OrderBusinessException("收货地址解析失败" + msg);
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        paramsMap.put("origin", shopLngLat);
        paramsMap.put("destination", userLngLat);
        paramsMap.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/riding",
                paramsMap);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            String msg = jsonObject.getString("message");
            log.warn(MessageConstant.ORDER_DELIVERY_PATH_PLANNING_FAILED + "：" + msg);
            throw new OrderBusinessException(MessageConstant.ORDER_DELIVERY_PATH_PLANNING_FAILED);
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException(MessageConstant.ORDER_BEYOND_DELIVERY_SCOPE);
        }
    }
}
